package cn.wolfcode.trip.base.filter;

import cn.wolfcode.trip.base.util.UploadUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


/**
 * @author mycp
 *
 * 图片过滤器, 只对/upload开头的资源起过滤作用
 */
@WebFilter("/upload/*")
public class ImageFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 获取到访问的资源路径 /upload/e6066b48-85ec-48c2-8c1d-4c2ed41fcacc.jpeg
        String uri = req.getRequestURI();
        // 获取图片文件名 e6066b48-85ec-48c2-8c1d-4c2ed41fcacc.jpeg
        String filename = uri.substring(uri.lastIndexOf('/') + 1);
        // 获取到文件保存在本地的解决路径 f:/upload/aba61437-23b1-41e8-bada-165b7ccc8722.png
        Path path = Paths.get(UploadUtil.imgDir, filename);
        if (Files.exists(path)) {
            // 设置响应回去的文本为图片格式
            resp.setContentType("image");
            // 复制图片输出给浏览器
            Files.copy(path, response.getOutputStream());
        } else {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void destroy() {}
}
